<?php
/**
 * Created by PhpStorm.
 * Script Name: AppInit.php
 * Create: 2022/9/19 19:15
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\bot\middleware;

use plugin\wechat\app\service\Bot as BotService;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class DataInit implements MiddlewareInterface
{
    /**
     * @inheritDoc
     */
    public function process(Request $request, callable $handler): Response
    {
        $app        = request()->getApp();
        $controller = request()->getController();
        $action     = request()->getAction();

        $controller_layer = explode('/', $controller);
        $controller = strtolower($controller_layer[count($controller_layer) - 1]);
        $request->controller = $controller;
        $request = $this->initBot($request);

        return $handler($request);
    }

    /**
     * 机器人接口数据接收处理
     * @param Request $request
     * @return Request
     * Author: fudaoji<fdj@kuryun.cn>
     */
    protected function initBot(Request $request){
        $request->ajaxData = $this->getAjax();
        $request->driver = strtolower(input('driver', BotService::PROTOCOL_MY));
        return $request;
    }

    private function getAjax()
    {
        $json = \request()->rawBody();
        return $json ? json_decode($json, true) : [];
    }
}